<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Ringo Chan <334258471@qq.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use Admin\Model\ProductCategoryModel;
/**
 * 商品控制器
 * 
 * @author Ringo Chan<334258471@qq.com>
 */
class ProductController extends AdminController{
    /**
     * 异步获取商品数据
     *
     * @param string query 编号或名称
     * @return array 编号、名称
     */
    public function product_autocomplete(){
        $title       =   I('query');
        $map['is_show']  =  1;

	    // if(I('get.type')=='score_show_img'){
		   //  $map['type']='score';
	    // }
        if(is_numeric($title)){
            $map['id|title']=   array(intval($title),array('like','%'.$title.'%'),'_multi'=>true);
        }else{
            $map['title']    =   array('like', '%'.(string)$title.'%');
        }
    	// var_dump($map);
        $list   = M('product')->where($map)->page(0, 20)->select();
    
        echo json_encode($list);
    }
    //抢购会商品
    public function product_autocomplete2(){
        $title       =   I('query');
        $map['is_show']  =  1;
        $map['in_special_panic'] = 1;
        if(is_numeric($title)){
            $map['id|title']=   array(intval($title),array('like','%'.$title.'%'),'_multi'=>true);
        }else{
            $map['title']    =   array('like', '%'.(string)$title.'%');
        }

        $list   = M('product')->where($map)->page(0, 20)->select();

        echo json_encode($list);
    }
    //积分商品
    public function product_autocomplete_score(){
        $title       =   I('query');
        $map['is_show']  =  1;
        $map['type'] = 'score';
        if(is_numeric($title)){
            $map['id|title']=   array(intval($title),array('like','%'.$title.'%'),'_multi'=>true);
        }else{
            $map['title']    =   array('like', '%'.(string)$title.'%');
        }

        $list   = M('product')->where($map)->page(0, 20)->select();

        echo json_encode($list);
    }
    /**
     * 正价商品区首页
     * 
     * @author Ringo Chan<334258471@qq.com>
     */
    public function index(){
        $title = I('title');
        $shop = I('shop');
        $nickname = I('nickname');
        
        $map['status']  =   array('egt', 0);
        
        if(is_numeric($title)){
            $map['id|title']=   array(intval($title),array('like','%'.$title.'%'),'_multi'=>true);
        }else{
            $map['title']    =   array('like', '%'.(string)$title.'%');
        }

	    $map['type'] = array('neq', 'score');
        if(!empty($shop)){
            $M_shop = M('shop');
            
            $shops = $M_shop->where(array('id|title'=>array(intval($shop),array('like','%'.$shop.'%'),'_multi'=>true)))->select();
            
            $map_shop = array();
            
            foreach ($shops as $shop) {
                $map_shop[] = $shop['id'];
            }
            
            $map['shop_id'] = array('in', $map_shop);
        }
        
        if(!empty($nickname)){
            $M_member = M('member');
        
            $users = $M_member->where(array('uid|nickname'=>array(intval($nickname),array('like','%'.$nickname.'%'),'_multi'=>true)))->select();
        
            $map_user = array();
        
            foreach ($users as $user) {
                $map_user[] = $user['uid'];
            }
        
            $map['uid'] = array('in', $map_user);
        }
        $map['good_type'] =1;
        $list   = $this->lists('Product', $map);
        foreach ($list as &$li){
            $product_img_id= M('product_image')->where('product_id='.$li['id'])->order('id asc')->find();
            $li['product_img']  = M('picture')->where('id='.$product_img_id['cover_id'])->getField('path');
            if($li['is_home_show']){
                $li['is_home'] = "是";
            }else{
                $li['is_home'] = "否";
            }
        }
        int_to_string($list, array('status'=>getStatus('product'), 'in_special_panic'=>getStatus(), 'in_special_gift'=>getStatus()));
        $this->assign('_type', $map['type']);
        $this->assign('_list', $list);
        $this->meta_title = '商品列表';
        $this->display('index');
    }
        /**
     * 普通商品首页
     *
     * @author Ringo Chan<334258471@qq.com>
     */
    public function score_list(){
        $title = I('title');
        $shop = I('shop');
        $nickname = I('nickname');

        $map['status']  =   array('egt', 0);

        if(is_numeric($title)){
            $map['id|title']=   array(intval($title),array('like','%'.$title.'%'),'_multi'=>true);
        }else{
            $map['title']    =   array('like', '%'.(string)$title.'%');
        }

        if(!empty($shop)){
            $M_shop = M('shop');

            $shops = $M_shop->where(array('id|title'=>array(intval($shop),array('like','%'.$shop.'%'),'_multi'=>true)))->select();

            $map_shop = array();

            foreach ($shops as $shop) {
                $map_shop[] = $shop['id'];
            }

            $map['shop_id'] = array('in', $map_shop);
        }
		$map['type'] = array('eq', 'score');
        if(!empty($nickname)){
            $M_member = M('member');

            $users = $M_member->where(array('uid|nickname'=>array(intval($nickname),array('like','%'.$nickname.'%'),'_multi'=>true)))->select();

            $map_user = array();

            foreach ($users as $user) {
                $map_user[] = $user['uid'];
            }

            $map['uid'] = array('in', $map_user);
        }

        $list   = $this->lists('Product', $map);
        int_to_string($list, array('status'=>getStatus('product'), 'in_special_panic'=>getStatus(), 'in_special_gift'=>getStatus()));
        $this->assign('_type', $map['type']);
        $this->assign('_list', $list);
        $this->meta_title = '商品列表';
        $this->display('score_list');
    }

    /**
     * 新增商品
     * 
     * @param string type 商品类型
     * @author Ringo Chan<334258471@qq.com>
     */
    public function add(){
        if (IS_POST){
    	    switch (I('post.type')) {
    	        case 'putong':

                    empty(I('post.title')) && $this->error('商品名称不能为空');
                    empty(I('post.price')) && $this->error('兑换所需元宝不能为空');
                    !(preg_match('/[\d]+$/', I('post.price')) && intval(I('post.price')) >= 0) && $this->error('请输入商品库存，不能小于0');
                    !(preg_match('/[\d]+$/', I('post.quantity')) && intval(I('post.quantity')) >= 0) && $this->error('请输入商品库存，不能小于0');

    	            $_POST['uid'] = 0;
    	            $_POST['in_special_panic'] = I('post.in_special_panic', 0);
    	            $_POST['in_special_gift'] = I('post.in_special_gift', 0);
    	            break;
		        case 'score':
			        !(is_numeric(I('post.use_score')) && I('post.use_score') > 0) && $this->error('请输入商品积分，不能小于1');
			        !(preg_match('/[\d]+$/', I('post.quantity')) && intval(I('post.quantity')) >= 0) && $this->error('请输入商品库存，不能小于0');
			        $_POST['in_special_panic'] = I('post.in_special_panic', 0);
			        $_POST['in_special_gift'] = I('post.in_special_gift', 0);
			        break;
                default:
                    break;
    	    }
    	    
    	    $_POST['create_time'] = NOW_TIME;
    	    $_POST['update_time'] = NOW_TIME;
    	    $is_home_show=I('post.is_home_show',0);
            $is_top=I('post.is_top',0);
            $slogan_title=I('post.slogan_title');
            
    	    $M_product = M('product');
    	    $data = $M_product->create();
    	    $id = $M_product->add($data);
    	    
    	    $id <= 0 && $this->error('添加失败，未知错误！');
    	    
    	    /* 商品图片 */
    	    $M_product_image = M('product_image');
    	    
    	    $pics = I('post.pic');
    	    
    	    foreach ($pics as $pic) {
    	        $M_product_image->add(array('product_id'=>$id, 'cover_id'=>$pic));
    	    }
    	    
    	    /* 商品专题 */
    	    if (I('post.type') == 'putong') {
    	        /* 商品专题 */
    	        $special_panic = I('post.panic');

    	        $data = array(
    	            'product_id' => $id,
    	            'special_panic_id' => empty($special_panic['special_panic_id']) ? 0 : $special_panic['special_panic_id'],
    	            'condition_price' => empty($special_panic['condition_price']) ? 0 : $special_panic['condition_price'],
    	            'discount' => empty($special_panic['discount']) ? : $special_panic['discount'],
    	            'create_time' => NOW_TIME
    	        );
    	    
    	        $M_product_special_panic = M('product_special_panic');
    	        $M_product_special_panic->add($data);
    	    
    	        $M_product_special_gift = M('product_special_gift');
    	        $special_gifts = I('post.gift');
    	    
    	        foreach ($special_gifts as $special_gift) {
    	            $data = array(
    	                'product_id' => $id,
    	                'special_gift_id' => $special_gift,
    	                'create_time' => NOW_TIME
    	            );
    	    
    	            $M_product_special_gift->add($data);
    	        }
    	    }
    	    
    	    $this->success('新增成功', I('post.type')=='score'?U('score_list'):U('index'));
        }else{
            $type = I('get.type');
            
            $M_product_type = M('product_type');
            $info['type'] = $type;
            $this->assign('paipinactivity_list',M('product_special_activity')->select());
            $this->assign('info', $info);
            $this->assign('category_tree', $this->getCategoryTree());
           // $this->meta_title = '新增'.$product_type['title'];
            $this->display('add'.$type);
        }
    }
    
    /**
     * 编辑商品
     *
     * @param integer id 商品编号
     * @author Ringo Chan<334258471@qq.com>
     */
    public function edit(){
        $id = I('get.id');
        
        $M_product = M('product');
        $info = $M_product->find($id);
        !$info && $this->error('非法的参数编号');
        
        if (IS_POST){
            	
            switch (I('post.type')) {
                case 'putong':
                    empty(I('post.title')) && $this->error('商品名称不能为空');
                    empty(I('post.price')) && $this->error('兑换所需元宝不能为空');
                    !(preg_match('/[\d]+$/', I('post.price')) && intval(I('post.price')) >= 0) && $this->error('请输入商品库存，不能小于0');
                    !(preg_match('/[\d]+$/', I('post.quantity')) && intval(I('post.quantity')) >= 0) && $this->error('请输入商品库存，不能小于0');
                    $_POST['in_special_panic'] = I('post.in_special_panic', 0);
                    $_POST['in_special_gift'] = I('post.in_special_gift', 0);
                    break;
	            case 'score':
		            !(is_numeric(I('post.use_score')) && I('post.use_score') > 0) && $this->error('请输入商品积分，不能小于1');
		            !(preg_match('/[\d]+$/', I('post.quantity')) && intval(I('post.quantity')) >= 0) && $this->error('请输入商品库存，不能小于0');
		            $_POST['in_special_panic'] = I('post.in_special_panic', 0);
		            $_POST['in_special_gift'] = I('post.in_special_gift', 0);
		            break;

                default:
    	           break;
            }
            
            $_POST['update_time'] = NOW_TIME;
            $is_home_show=I('post.is_home_show',0);
            $is_top=I('post.is_top',0);
            $slogan_title=I('post.slogan_title');
            
            
            $M_product = M('product');
            $data = $M_product->create();
            $data['is_home_show']=$is_home_show;
            $data['is_top']=$is_top;
           
            $M_product->save($data) === false && $this->error('编辑失败，未知错误！');
            
            /* 商品图片 */
            $M_product_image = M('product_image');
            $M_product_image->where(array('product_id'=>$id))->delete();
            	
            $pics = I('post.pic');
            
            foreach ($pics as $pic) {
                $M_product_image->add(array('product_id'=>$id, 'cover_id'=>$pic));
            }
            
            if (I('post.type') == 'putong') {
                /* 商品专题 */
                $special_panic = I('post.panic');
                
                $data = array(
                    'product_id' => $id,
                    'special_panic_id' => empty($special_panic['special_panic_id']) ? 0 : $special_panic['special_panic_id'],
                    'condition_price' => empty($special_panic['condition_price']) ? 0 : $special_panic['condition_price'],
                    'discount' => empty($special_panic['discount']) ? : $special_panic['discount'],
                    'create_time' => NOW_TIME
                );
                
                $M_product_special_panic = M('product_special_panic');
                $M_product_special_panic->where(array('product_id'=>$id))->delete();
                $M_product_special_panic->add($data);
                
                $M_product_special_gift = M('product_special_gift');
                $M_product_special_gift->where(array('product_id'=>$id))->delete();
                $special_gifts = I('post.gift');
                
                foreach ($special_gifts as $special_gift) {
                    $data = array(
                        'product_id' => $id,
                        'special_gift_id' => $special_gift,
                        'create_time' => NOW_TIME
                    );
                
                    $M_product_special_gift->add($data);
                }
            }

            $this->success('编辑成功', I('post.type')=='score'?U('score_list'):U('index'));
        }else{
            $type = $info['type'];
            

            $M_product_image = M('product_image');
            $pics = $M_product_image->where(array('product_id'=>$id))->order('id ASC')->select();

            switch ($type) {
                case 'putong':
                    $M_product_special_panic = M('product_special_panic');
                    $info['panic'] = $M_product_special_panic->where(array('product_id'=>$id))->find();
                    
                    $M_product_special_gift = M('product_special_gift');
                    $info['gift'] = $M_product_special_gift->where(array('product_id'=>$id))->select();
                    
                    $M_product_option = M('product_option');
                    $info['options'] = list_to_tree($M_product_option->where(array('product_id'=>$id))->select());
                    
                    $M_product_option_price = M('product_option_price');
                    $info['option_prices'] = $M_product_option_price->where(array('product_id'=>$id))->select();
                    break;
                default:
                    break;
            }
            //var_dump($type);
            $this->assign('paipinactivity_list',M('product_special_activity')->select());
            $this->assign('info', $info);
            $this->assign('pics', $pics);
            $this->assign('category_tree', $this->getCategoryTree());
            //$this->meta_title = '编辑'.$product_type['title'];
            $this->display('edit'.$type);
        }
    }
    
    /**
     * 删除商品
     * 
     * @author Ringo Chan<334258471@qq.com>
     */
    public function delete(){
        $ids = I('id');
        
        if(empty($ids)){
            $this->error('请选择要操作的数据');
        }
        
        $M_product = M('product');
        
        $map    =   array();
        
        if(is_array($ids)){
            $map['id'] = array('in', $ids);
        }elseif (is_numeric($ids)){
            $map['id'] = $ids;
        }
        
        $M_product->where($map)->delete()!==false ? $this->success('删除成功！','',IS_AJAX) : $this->error('删除失败！','',IS_AJAX);
    }
    
    public function group() {
        $list = $this->lists('product_group');
        $this->assign('_list', $list);
        $this->meta_title = '分类模块';
        $this->display('group');
    }
    
    public function addGroup() {
        $ProductGroup = D('product_group');
    
        if (IS_POST) {
            $data = $ProductGroup->create();
            $data || $this->error($ProductGroup->getError());
            $res = $ProductGroup->add();
            $res !== false ? $this->success('新增成功！', U('group')) : $this->error('未知错误');
        }
    
        $this->meta_title = '新增分类模块';
        $this->display('edit_group');
    }
    
    public function editGroup() {
        $ProductGroup = D('product_group');
        $id = I('get.id');
        $info = $ProductGroup->find($id);
        $info || $this->error('参数有误');
    
        if (IS_POST) {
            $data = $ProductGroup->create();
            $data || $this->error($ProductGroup->getError());
            $res = $ProductGroup->where(array('id'=>$id))->save();
            $res !== false ? $this->success('编辑成功！', U('group')) : $this->error('未知错误');
        }
    
        $this->assign('info', $info);
        $this->meta_title = '编辑分类模块';
        $this->display('edit_group');
    }
    
    public function deleteGroup() {
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['id'] =   array('in',$id);
        $res = D('product_group')->where($map)->delete();
        $res !== false ? $this->success('删除成功！') : $this->error('删除失败！');
    }
    
    /**
     * 商品分类首页
     * 
     * @author Ringo Chan<334258471@qq.com>
     */
    public function category($pid = 0){
        $title = I('title');
        /*         
        if (!empty($pid)) {
            $parent = M('Product_category')->find($pid);
            if (!empty($parent)) {
                if ($parent['pid'] != 0) {
                    $this->error('已经是最低节点');
                }
        
                $this->assign('parent', $parent);
            }
        }
        */        
        $map['status']  =   array('egt', 0);
        $map['pid'] = $pid;
        if ($pid) {
            $parent = M('product_category')->find($pid);
            $parent || $this->error('参数有误');
            $this->assign('parent', $parent);
        }
        if(is_numeric($title)){
            $map['id|title']=   array(intval($title),array('like','%'.$title.'%'),'_multi'=>true);
        }else{
            $map['title']    =   array('like', '%'.(string)$title.'%');
        }
        
        Cookie('__forward__',$_SERVER['REQUEST_URI']);
        
        $list   = $this->lists('product_category', $map);
        int_to_string($list);
        $this->assign('_list', $list);
        $this->assign('pid', $pid);
        $this->meta_title = '商品分类';
        $this->display('category');
    }
    
    /**
     * 新增商品分类
     * 
     * @author Ringo Chan<334258471@qq.com>
     */
    public function addCategory(){
        if(IS_POST){
            $M_product_category = D('product_category');
            $data = $M_product_category->create();
            if($data){
                $id = $M_product_category->add();
                if($id){
                    $parent = $M_product_category->find($data['pid']);
                    $path = $parent ? $parent['path'] . $id . ProductCategoryModel::PATH_SEPARATOR : ProductCategoryModel::PATH_SEPARATOR . $id . ProductCategoryModel::PATH_SEPARATOR;
                    $M_product_category->where(array('id'=>$id))->save(array('path'=>$path));
                    action_log('update_product_category', 'Product_category', $id, UID);
                    $this->success('新增成功', Cookie('__forward__'));
                } else {
                    $this->error('新增失败');
                }
            } else {
                $this->error($M_product_category->getError());
            }
        } else {
            $this->assign('pid', I('get.pid', 0));
            $this->assign('groups', M('product_group')->select());
            $this->meta_title = '新增分类';
            $this->display('editcategory');
        }
    }
    
    /**
     * 编辑商品分类
     * 
     * @param integer $id
     * @author Ringo Chan <334258471@qq.com>
     */
    public function editCategory($id = 0) {
        $M_product_category = D('product_category');
        $info = $M_product_category->find($id);
        
        !$info && $this->error('非法参数编号');
        
        if(IS_POST){
            $data = $M_product_category->create();
            if($data){
                if($M_product_category->save()!== false){
                    action_log('update_project_catalog', 'Project_catalog', $data['id'], UID);
                    $this->success('更新成功', Cookie('__forward__'));
                } else {
                    $this->error($M_product_category->getError());
                }
            } else {
                $this->error($M_product_category->getError());
            }
        } else {
            $this->assign('pid', $info['pid']);
            $this->assign('groups', M('product_group')->select());
            $this->assign('info', $info);
            $this->meta_title = '编辑分类';
            $this->display('editcategory');
        }
    }
    
    /**
     * 删除商品分类
     * 
     * @param array $id
     * @author Ringo Chan <334258471@qq.com>
     */
    public function deleteCategory(){
        $ids = I('id');
        
        if(empty($ids)){
            $this->error('请选择要操作的数据');
        }
        
        $M_product_category = M('product_category');
        
        $map    =   array();
        if(is_array($ids)){
            $map['pid'] = array('in', $ids);
        }elseif (is_numeric($ids)){
            $map['pid'] = $ids;
        }
        
        $children = $M_product_category->where($map)->field('id')->select();
        
        foreach ($children as $child) {
            $ids[] = $child['id'];
        }
        
        $map    =   array();
        if(is_array($ids)){
            $map['id'] = array('in', $ids);
        }elseif (is_numeric($ids)){
            $map['id'] = $ids;
        }
        
        if($M_product_category->where($map)->delete()!==false){
            $this->success('删除成功！','',IS_AJAX);
        }else{
            $this->error('删除失败！','',IS_AJAX);
        }
    }
    
    /**
     * 新增/编辑 商品选项
     * 
     * @param integer id 商品选项编号
     * @param integer pid 商品选项父级编号
     * @param string text 商品选项属性值
     * @author Ringo Chan <334258471@qq.com>
     */
    public function editOption($id = 0, $pid = 0, $product_id = 0, $text = ''){
        $M_product = M('product');
        $M_product_option = M('product_option');
        
        if (empty($id) && empty($pid)) {
            empty($product_id) && !$M_product->find($product_id) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
            empty($text) && $this->ajaxReturn(array('status'=>0, 'message'=>'选项标题不能为空'));
            
            $id = $M_product_option->add(array('product_id'=>$product_id, 'pid'=>0, 'title'=>$text, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
        } elseif (empty($id)) {
            empty($text) && $this->ajaxReturn(array('status'=>0, 'message'=>'属性标题不能为空'));
            empty($pid) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
            
            $info = $M_product_option->find($pid);
            !$info && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
            
            $id = $M_product_option->add(array('product_id'=>$info['product_id'], 'pid'=>$pid, 'title'=>$text, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
        } else {
            empty($text) && $this->ajaxReturn(array('status'=>0, 'message'=>'属性标题不能为空'));
            !$M_product_option->find($id) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
            
            $M_product_option->where(array('id'=>$id))->save(array('title'=>$text, 'update_time'=>NOW_TIME));
        }
        
        $this->ajaxReturn(array('status'=>1, 'message'=>'操作成功', 'data'=>array('id'=>$id)));
    }
    
    /**
     * 删除 商品选项
     * 
     * @author Ringo Chan <334258471@qq.com>
     */
    public function deleteOption($id = 0){
        $M_product_option = M('product_option');
        
        !$M_product_option->find($id) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
        $product_id = $M_product_option->where(array('id|pid'=>$id))->getField('product_id');
        $M_product_option->where(array('id|pid'=>$id))->delete();
//        var_dump($product_id);
        $map['product_option_id'] = array('like','%'.$id.'%');
        $map['product_id'] =$product_id;
        M('product_option_price')->where($map)->delete();
        //echo M('product_option_price')->getLastSql();

        
        $this->ajaxReturn(array('status'=>1, 'message'=>'操作成功'));
    }

    /**
     * 删除 商品选项
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function deleteOption2($id = 0){
        $M_product_option = M('product_option');

        !$M_product_option->find($id) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
        $option=$M_product_option->where(array('pid'=>$id))->select();

        $product_id = $M_product_option->where(array('id|pid'=>$id))->getField('product_id');
        $M_product_option->where(array('id|pid'=>$id))->delete();
//        var_dump($product_id);
        foreach ($option as $opt) {
            $map['product_option_id'] = array('like', '%' . $opt['id'] . '%');
            $map['product_id'] = $product_id;
            M('product_option_price')->where($map)->delete();
          //  echo M('product_option_price')->getLastSql();
        }



        $this->ajaxReturn(array('status'=>1, 'message'=>'操作成功'));
    }
    
    /**
     * 增加 商品选项价钱
     * 
     * @author Ringo Chan <334258471@qq.com>
     */
    public function addOptionPrice($product_id = 0, $ids = 0, $price = 0){
        $M_product = M('product');
        $M_product_option = M('product_option');
        $M_product_option_price = M('product_option_price');
        
        empty($product_id) && !$M_product->find($product_id) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
        empty($ids) && $this->ajaxReturn(array('status'=>0, 'message'=>'请选择选项'));
        !is_numeric($price) && $price <= 0 && $this->ajaxReturn(array('status'=>0, 'message'=>'价格不能低于1元'));
        
        !is_array($ids) && $ids = str2arr($ids);
        
        $option_category_count = $M_product_option->where(array('product_id' => $product_id, 'pid'=>0))->count();
        count($ids) != $option_category_count && $this->ajaxReturn(array('status'=>0, 'message'=>'缺少组合选项'));
        
        sort($ids, SORT_NUMERIC);
        $ids = arr2str($ids);
        $info = $M_product_option_price->where(array('product_id'=>$product_id, 'product_option_id'=>$ids))->find();
        
        $info && $this->ajaxReturn(array('status'=>0, 'message'=>'组合选项已存在'));
        
        $id = $M_product_option_price->add(array('product_id'=>$product_id, 'product_option_id'=>$ids, 'price'=>$price, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
        
        $id > 0 ? $this->ajaxReturn(array('status'=>1, 'message'=>'操作成功', 'data'=>array('id'=>$id))) : array('status'=>0, 'message'=>'未知错误');
    }
    
    /**
     * 修改 商品选项价钱
     */
    public function editOptionPrice($id = 0, $price = 0) {
        $M_product_option_price = M('product_option_price');
        
        !$M_product_option_price->find($id) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
        !is_numeric($price) && $price <= 0 && $this->ajaxReturn(array('status'=>0, 'message'=>'价格不能低于1元'));
        
        $boolean = $M_product_option_price->where(array('id'=>$id))->setField(array('price'=>$price, 'update_time'=>NOW_TIME));
        
        $boolean ? $this->ajaxReturn(array('status'=>1, 'message'=>'操作成功', 'data'=>array('id'=>$id))) : array('status'=>0, 'message'=>'未知错误');
    }
    
    /**
     * 删除 商品选项价钱
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function deleteOptionPrice($id = 0){
        $M_product_option_price = M('product_option_price');
    
        !$M_product_option_price->find($id) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
    
        $M_product_option_price->where(array('id'=>$id))->delete();
    
        $this->ajaxReturn(array('status'=>1, 'message'=>'操作成功'));
    }
    
    /**
     * 状态修改
     * 
     * @author Ringo Chan <334258471@qq.com>
     */
    public function changeStatus($method=null){
        $id = array_unique((array)I('id',0));
    
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['id'] =   array('in',$id);
        switch ( strtolower($method) ){
            case 'forbidcategory':
                $this->forbid('Product_category', $map);
                break;
            case 'resumecategory':
                $this->resume('Product_category', $map);
                break;
            default:
                $this->error('参数非法');
        }
    }
    
    /**
     * 获取商品分类树
     * 
     * @return Ambigous <multitype:, mixed>
     */
    private function getCategoryTree(){
        $M_product_category = M('product_category');
        $list = $M_product_category->order('sort ASC')->select();
        $list = list_to_tree($list);
        return $list;
    }


    /**
     * 限时抢购区首页
     *
     * @author Ringo Chan<334258471@qq.com>
     */
    public function xianshiList(){
        $title = I('title');
        $shop = I('shop');
        $nickname = I('nickname');

        $map['status']  =   array('egt', 0);

        if(is_numeric($title)){
            $map['id|title']=   array(intval($title),array('like','%'.$title.'%'),'_multi'=>true);
        }else{
            $map['title']    =   array('like', '%'.(string)$title.'%');
        }

        $map['type'] = array('neq', 'score');
        $map['good_type'] =2;
        $list   = $this->lists('Product', $map);
        foreach ($list as &$li){
            $product_img_id= M('product_image')->where('product_id='.$li['id'])->order('id asc')->find();
            $li['product_img']  = M('picture')->where('id='.$product_img_id['cover_id'])->getField('path');
            if($li['is_home_show']){
                $li['is_home'] = "是";
            }else{
                $li['is_home'] = "否";
            }
        }
        int_to_string($list, array('status'=>getStatus('product'), 'in_special_panic'=>getStatus(), 'in_special_gift'=>getStatus()));
        $this->assign('_type', $map['type']);
        $this->assign('_list', $list);
        $this->meta_title = '商品列表';
        $this->display('xianshiList');
    }

    /**
     * 新增商品
     *
     * @param string type 商品类型
     * @author Ringo Chan<334258471@qq.com>
     */
    public function xianshi_add(){
        if (IS_POST){
            switch (I('post.type')) {
                case 'putong':

                    empty(I('post.title')) && $this->error('商品名称不能为空');
                    empty(I('post.price')) && $this->error('兑换所需元宝不能为空');
                    !(preg_match('/[\d]+$/', I('post.price')) && intval(I('post.price')) >= 0) && $this->error('请输入商品库存，不能小于0');
                    !(preg_match('/[\d]+$/', I('post.quantity')) && intval(I('post.quantity')) >= 0) && $this->error('请输入商品库存，不能小于0');

                    $_POST['uid'] = 0;
                    $_POST['in_special_panic'] = I('post.in_special_panic', 0);
                    $_POST['in_special_gift'] = I('post.in_special_gift', 0);
                    break;
                case 'score':
                    !(is_numeric(I('post.use_score')) && I('post.use_score') > 0) && $this->error('请输入商品积分，不能小于1');
                    !(preg_match('/[\d]+$/', I('post.quantity')) && intval(I('post.quantity')) >= 0) && $this->error('请输入商品库存，不能小于0');
                    $_POST['in_special_panic'] = I('post.in_special_panic', 0);
                    $_POST['in_special_gift'] = I('post.in_special_gift', 0);
                    break;
                default:
                    break;
            }

            $_POST['create_time'] = NOW_TIME;
            $_POST['update_time'] = NOW_TIME;
            $is_home_show=I('post.is_home_show',0);
            $is_top=I('post.is_top',0);
            $slogan_title=I('post.slogan_title');

            $M_product = M('product');
            $data = $M_product->create();
            $data['good_type']=2;
            $data['y_price']=I('y_price');


            $id = $M_product->add($data);

            $id <= 0 && $this->error('添加失败，未知错误！');

            /* 商品图片 */
            $M_product_image = M('product_image');

            $pics = I('post.pic');

            foreach ($pics as $pic) {
                $M_product_image->add(array('product_id'=>$id, 'cover_id'=>$pic));
            }

            /* 商品专题 */
            if (I('post.type') == 'putong') {
                /* 商品专题 */
                $special_panic = I('post.panic');

                $data = array(
                    'product_id' => $id,
                    'special_panic_id' => empty($special_panic['special_panic_id']) ? 0 : $special_panic['special_panic_id'],
                    'condition_price' => empty($special_panic['condition_price']) ? 0 : $special_panic['condition_price'],
                    'discount' => empty($special_panic['discount']) ? : $special_panic['discount'],
                    'create_time' => NOW_TIME
                );

                $M_product_special_panic = M('product_special_panic');
                $M_product_special_panic->add($data);

                $M_product_special_gift = M('product_special_gift');
                $special_gifts = I('post.gift');

                foreach ($special_gifts as $special_gift) {
                    $data = array(
                        'product_id' => $id,
                        'special_gift_id' => $special_gift,
                        'create_time' => NOW_TIME
                    );

                    $M_product_special_gift->add($data);
                }
            }

            $this->success('新增成功', I('post.type')=='score'?U('score_list'):U('xianshiList'));
        }else{
            $type = I('get.type');

            $M_product_type = M('product_type');
            $info['type'] = $type;
            $this->assign('paipinactivity_list',M('product_special_activity')->select());
            $this->assign('info', $info);
            $this->assign('category_tree', $this->getCategoryTree());
            // $this->meta_title = '新增'.$product_type['title'];
            $this->display('addputong_xianshi');
        }
    }

    /**
     * 编辑商品
     *
     * @param integer id 商品编号
     * @author Ringo Chan<334258471@qq.com>
     */
    public function xianshi_edit(){
        $id = I('id');

        $M_product = M('product');
        $info = $M_product->find($id);
        !$info && $this->error('非法的参数编号');

        if (IS_POST){

            switch (I('post.type')) {
                case 'putong':
                    empty(I('post.title')) && $this->error('商品名称不能为空');
                    empty(I('post.price')) && $this->error('兑换所需元宝不能为空');
                    !(preg_match('/[\d]+$/', I('post.price')) && intval(I('post.price')) >= 0) && $this->error('请输入商品库存，不能小于0');
                    !(preg_match('/[\d]+$/', I('post.quantity')) && intval(I('post.quantity')) >= 0) && $this->error('请输入商品库存，不能小于0');
                    $_POST['in_special_panic'] = I('post.in_special_panic', 0);
                    $_POST['in_special_gift'] = I('post.in_special_gift', 0);
                    break;
                case 'score':
                    !(is_numeric(I('post.use_score')) && I('post.use_score') > 0) && $this->error('请输入商品积分，不能小于1');
                    !(preg_match('/[\d]+$/', I('post.quantity')) && intval(I('post.quantity')) >= 0) && $this->error('请输入商品库存，不能小于0');
                    $_POST['in_special_panic'] = I('post.in_special_panic', 0);
                    $_POST['in_special_gift'] = I('post.in_special_gift', 0);
                    break;

                default:
                    break;
            }

            $_POST['update_time'] = NOW_TIME;
            $is_home_show=I('post.is_home_show',0);
            $is_top=I('post.is_top',0);
            $slogan_title=I('post.slogan_title');


            $M_product = M('product');
            $data = $M_product->create();
            $data['y_price']=I('y_price');
            $data['is_home_show']=$is_home_show;
            $data['is_top']=$is_top;

            $M_product->save($data) === false && $this->error('编辑失败，未知错误！');

            /* 商品图片 */
            $M_product_image = M('product_image');
            $M_product_image->where(array('product_id'=>$id))->delete();

            $pics = I('post.pic');

            foreach ($pics as $pic) {
                $M_product_image->add(array('product_id'=>$id, 'cover_id'=>$pic));
            }

            if (I('post.type') == 'putong') {
                /* 商品专题 */
                $special_panic = I('post.panic');

                $data = array(
                    'product_id' => $id,
                    'special_panic_id' => empty($special_panic['special_panic_id']) ? 0 : $special_panic['special_panic_id'],
                    'condition_price' => empty($special_panic['condition_price']) ? 0 : $special_panic['condition_price'],
                    'discount' => empty($special_panic['discount']) ? : $special_panic['discount'],
                    'create_time' => NOW_TIME
                );

                $M_product_special_panic = M('product_special_panic');
                $M_product_special_panic->where(array('product_id'=>$id))->delete();
                $M_product_special_panic->add($data);

                $M_product_special_gift = M('product_special_gift');
                $M_product_special_gift->where(array('product_id'=>$id))->delete();
                $special_gifts = I('post.gift');

                foreach ($special_gifts as $special_gift) {
                    $data = array(
                        'product_id' => $id,
                        'special_gift_id' => $special_gift,
                        'create_time' => NOW_TIME
                    );

                    $M_product_special_gift->add($data);
                }
            }

            $this->success('编辑成功', I('post.type')=='score'?U('score_list'):U('xianshiList'));
        }else{
            $type = $info['type'];


            $M_product_image = M('product_image');
            $pics = $M_product_image->where(array('product_id'=>$id))->order('id ASC')->select();

            switch ($type) {
                case 'putong':
                    $M_product_special_panic = M('product_special_panic');
                    $info['panic'] = $M_product_special_panic->where(array('product_id'=>$id))->find();

                    $M_product_special_gift = M('product_special_gift');
                    $info['gift'] = $M_product_special_gift->where(array('product_id'=>$id))->select();

                    $M_product_option = M('product_option');
                    $info['options'] = list_to_tree($M_product_option->where(array('product_id'=>$id))->select());

                    $M_product_option_price = M('product_option_price');
                    $info['option_prices'] = $M_product_option_price->where(array('product_id'=>$id))->select();
                    break;
                default:
                    break;
            }
            //var_dump($type);
            $this->assign('paipinactivity_list',M('product_special_activity')->select());
            $this->assign('info', $info);
            $this->assign('pics', $pics);
            $this->assign('category_tree', $this->getCategoryTree());
            //$this->meta_title = '编辑'.$product_type['title'];
            $this->display('editputong_xianshi');
        }
    }

    /**
     * 删除商品
     *
     * @author Ringo Chan<334258471@qq.com>
     */
    public function xianshi_delete(){
        $ids = I('id');

        if(empty($ids)){
            $this->error('请选择要操作的数据');
        }

        $M_product = M('product');

        $map    =   array();

        if(is_array($ids)){
            $map['id'] = array('in', $ids);
        }elseif (is_numeric($ids)){
            $map['id'] = $ids;
        }

        $M_product->where($map)->delete()!==false ? $this->success('删除成功！','',IS_AJAX) : $this->error('删除失败！','',IS_AJAX);
    }
}